package com.wj.blog.controller;

import com.wj.blog.enums.ResultEnum;
import com.wj.blog.enums.StateEnums;
import com.wj.blog.pojo.Admin;
import com.wj.blog.service.AdminService;

import com.wj.blog.utils.Result;
import com.wj.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:   wj
 * Date:     2020/4/9 22:19
 * Description: 管理员接口
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    AdminService adminService;

    @PostMapping("/login")
    public Result<Object> login(@RequestBody Admin admin){
        if (admin==null){
            return new Result<Object>(ResultEnum.PARAMS_NULL.getCode(),ResultEnum.PARAMS_NULL.getMsg());
        }
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken authenticationToken = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());

        try {
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new Result<Object>(ResultEnum.PARAMS_NULL.getCode(),"用户名密码错误");
        }
        //登陆成功
        Serializable sessionId = subject.getSession().getId();
        Map<String,Object> returnMap = new HashMap<>(2);
        returnMap.put("token",sessionId);
        return new Result<Object>(returnMap);
    }
    @PutMapping("/update")
    public Result update(@RequestBody Admin admin){
        adminService.update(admin);
        return new Result("修改成功");
    }

}
